﻿#region Copyright ©2008-2010, Technische Universitaet Muenchen
// ====================================================================================================
//
// Last Changed by       $Author: then $
// Last Changed Date     $LastChangedDate: 2009-05-16 14:58:56 +0200 (Sat, 16 May 2009) $
// Last Changed Revision $Rev: 144 $
//
// ====================================================================================================
#endregion

using System.Xml;
using Tum.CollabXT.TFS.Resources;

namespace Tum.CollabXT.TFS
{
    public class GroupsAndPermissions : IProcessor
    {
        #region IProcessor Members

        public void Process(IProcessProvider processProvider, TFSToolProvider toolProvider)
        {
            string gapTemplateFileName = toolProvider.OutputPath + "/Groups and Permissions/GroupsandPermissions.xml";

            #region Load template
            XmlDocument gapDoc = new XmlDocument();
            toolProvider.ProcessLog.AddEntry(Language.Groups_Loading);
            try
            {
                gapDoc.Load(gapTemplateFileName);
            }
            catch
            {
                toolProvider.ProcessLog.AddEntryAndThrowException(string.Format(Language.Error_LoadingFailed, gapTemplateFileName));
            }
            #endregion

            toolProvider.ProcessLog.AddEntry(Language.Groups_SelectingNode);
            var groupsNode = gapDoc.SelectSingleNode("/tasks/task[@id=\"GroupCreation\"]/taskXml/groups");
            if (groupsNode == null)
                toolProvider.ProcessLog.AddEntryAndThrowException(Language.Error_NotFound_InvalidTemplate);

            //Get node which presents the default permission
            XmlNode defaultPermissionsNode = gapDoc.SelectSingleNode("//group[@name='Readers']");

            //Write
            foreach (IRole curRole in processProvider.Roles)
            {
                toolProvider.ProcessLog.AddEntry(string.Format(Language.Groups_WritingRole, curRole.Name));

                XmlNode newRoleNode = defaultPermissionsNode.CloneNode(true);
                newRoleNode.Attributes["name"].Value = curRole.Name;
                newRoleNode.Attributes["description"].Value = Helper.PreapareStringForTFS(curRole.Description, Helper.TFS_MaxWorkItemTextLen);

                groupsNode.AppendChild(newRoleNode);
            }

            #region Save groups and permissions file
            toolProvider.ProcessLog.AddEntry(Language.Groups_Saving);
            try
            {
                gapDoc.Save(gapTemplateFileName);
            }
            catch
            {
                toolProvider.ProcessLog.AddEntryAndThrowException(string.Format(Language.Error_SavingFailed, gapTemplateFileName));
            }
            #endregion
        }

        #endregion
    }
}